﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SportsPlatform.PermissionManagement.IPermissionManagement;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Query.PermissionManagement.FunctionInfo;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Dto.PermissionManagement.FunctionInfo;
using SportsPlatform.Query.PermissionManagement.BaseQuery;
using Abp.Application.Services;
using Abp.Domain.Repositories;
using SportsPlatform.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Global;
using Abp.Collections.Extensions;

namespace SportsPlatform.PermissionManagement.PermissionManagement
{
    /// <summary>
    /// 功能架构表
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class FunctionInfoService : SportsPlatformAppServiceBase, IFunctionInfoService
    {
        private readonly IRepository<FunctionInfo, Guid> _functionInfoRepository;

        private readonly IRepository<UserInfo, Guid> _userinfoRepository;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="functionInfoRepository"></param>
        /// <param name="userinfoRepository"></param>
        public FunctionInfoService(IRepository<FunctionInfo, Guid> functionInfoRepository, IRepository<UserInfo, Guid> userinfoRepository,
            IHttpContextAccessor context) : base(context)
        {
            _functionInfoRepository = functionInfoRepository;
            _userinfoRepository = userinfoRepository;
        }

        /// <summary>
        /// 添加信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddFunctionInfo(AddFunctionInfoQuery query)
        {
            BaseResultDto basePage = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                if (query.ParentId == null)
                {
                    query.ParentId = Guid.Empty;
                }
                FunctionInfo functionInfo = ObjectMapper.Map<FunctionInfo>(query);
                functionInfo.CreateUserId = token.Id;
                functionInfo.CreateTime = DateTime.Now;
                //判断父菜单是否存在
                if (query.ParentId != Guid.Empty)
                {
                    if ((await _functionInfoRepository.FirstOrDefaultAsync(info => info.Id == query.ParentId)) == null)
                    {
                        basePage.IsSuccess = false;
                        basePage.Code = HttpResultCode.Fail;
                        basePage.Message = "ParentId不存在！";
                        return basePage;
                    }
                }
                await _functionInfoRepository.InsertAsync(functionInfo);
                basePage.IsSuccess = true;
                basePage.Code = HttpResultCode.Success;
                basePage.Message = "新增成功！";
            }
            catch (Exception e)
            {
                basePage.IsSuccess = false;
                basePage.Code = HttpResultCode.Error;
                basePage.Message = e.Message.ToString();
            }
            return basePage;
        }

        /// <summary>
        /// 根据Id删除信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> DeleteFunctionInfo(DeleteOrGetModelQuery query)
        {
            BaseResultDto basePage = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var functionInfo = _functionInfoRepository.FirstOrDefault(info => info.Id == query.Id);
                if (functionInfo != null)
                {
                    functionInfo.DeleteUserId = token.Id;
                    functionInfo.IsDeleted = true;
                    functionInfo.DeleteTime = DateTime.Now;
                    await _functionInfoRepository.UpdateAsync(functionInfo);
                    basePage.IsSuccess = true;
                    basePage.Code = HttpResultCode.Success;
                    basePage.Message = "删除成功！";
                }
                else
                {
                    basePage.IsSuccess = false;
                    basePage.Code = HttpResultCode.Fail;
                    basePage.Message = "删除失败！未查到有效的数据！ ";
                }
            }
            catch (Exception e)
            {
                basePage.IsSuccess = false;
                basePage.Code = HttpResultCode.Error;
                basePage.Message = e.Message.ToString();
            }
            return basePage;
        }

        /// <summary>
        /// 根据Id查询信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetFunctionInfoDto>> GetFunctionInfo(DeleteOrGetModelQuery query)
        {
            ResultDto<GetFunctionInfoDto> resultDto = new ResultDto<GetFunctionInfoDto>();
            try
            {
                var functionInfo = await _functionInfoRepository.FirstOrDefaultAsync(info => info.Id == query.Id);
                if (functionInfo != null)
                {
                    if (functionInfo.IsDeleted == true)
                    {
                        resultDto.IsSuccess = false;
                        resultDto.Code = HttpResultCode.Fail;
                        resultDto.Message = "查询的数据已删除！";
                    }
                    else
                    {
                        resultDto.IsSuccess = true;
                        resultDto.Code = HttpResultCode.Success;
                        resultDto.Message = "查询成功！";
                        var functionInfoDto = ObjectMapper.Map<GetFunctionInfoDto>(functionInfo);
                        functionInfoDto.ParentName = functionInfoDto.ParentId != Guid.Empty ? _functionInfoRepository.FirstOrDefault(info => info.Id == functionInfoDto.ParentId).FunctionName : "";
                        functionInfoDto.ParentNumber = functionInfoDto.ParentId != Guid.Empty ? _functionInfoRepository.FirstOrDefault(info => info.Id == functionInfoDto.ParentId).FunctionNumber : "";
                        resultDto.Data = functionInfoDto;
                    }
                }
                else
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.Message = "未查询到数据！";
                }
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取所有下级List
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetFunctionInfoTreeDto>> GetFunctionInfoChildList(GetFunctionInfoTreeQuery query)
        {
            ResultListDto<GetFunctionInfoTreeDto> resultListDto = new ResultListDto<GetFunctionInfoTreeDto>();
            try
            {
                //为空标识获取所有
                var functioninfolist = query.ParentId == null ? await _functionInfoRepository.GetAllListAsync(info => info.ParentId == Guid.Empty && info.States == true && info.IsDeleted == false) : await _functionInfoRepository.GetAllListAsync(info => info.Id == query.ParentId && info.States == true && info.IsDeleted == false);
                if (functioninfolist != null && functioninfolist.Count > 0)
                {
                    resultListDto.IsSuccess = true;
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.Message = "查询成功！";
                    resultListDto.Count = functioninfolist.Count;
                    var functioninfolistdto = ObjectMapper.Map<List<GetFunctionInfoTreeDto>>(functioninfolist);
                    var functionlist = await _functionInfoRepository.GetAllListAsync();
                    functioninfolistdto.ForEach(item =>
                    {
                        item.ParentName = item.ParentId != Guid.Empty ? functionlist.Where(info => info.Id == item.ParentId).FirstOrDefault()?.FunctionName : "";
                        item.ParentNumber = item.ParentId != Guid.Empty ? functioninfolist.Where(info => info.Id == item.ParentId).FirstOrDefault()?.FunctionNumber : "";
                        item.Children = GetFunctionInfoTreeList(item.Id);
                    });
                    resultListDto.Data = functioninfolistdto;
                }
                else
                {
                    resultListDto.IsSuccess = false;
                    resultListDto.Code = HttpResultCode.Fail;
                    resultListDto.Message = "未查询到数据！";
                }
            }
            catch (Exception e)
            {
                resultListDto.IsSuccess = false;
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.Message = e.Message.ToString();
            }
            return resultListDto;
        }
        /// <summary>
        /// 递归获取树型菜单
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public List<GetFunctionInfoTreeDto> GetFunctionInfoTreeList(Guid ParentId)
        {
            List<GetFunctionInfoTreeDto> resultListDto = new List<GetFunctionInfoTreeDto>();
            try
            {
                var functioninfolist = _functionInfoRepository.GetAllList(info => info.ParentId == ParentId && info.States == true && info.IsDeleted == false);
                if (functioninfolist != null && functioninfolist.Count > 0)
                {
                    resultListDto = ObjectMapper.Map<List<GetFunctionInfoTreeDto>>(functioninfolist);
                    var funclist = _functionInfoRepository.GetAllList();
                    resultListDto.ForEach(item =>
                    {
                        item.ParentName = item.ParentId != Guid.Empty ? funclist.Where(info => info.Id == item.ParentId).FirstOrDefault().FunctionName : "";
                        item.ParentNumber = item.ParentId != Guid.Empty ? funclist.Where(info => info.Id == item.ParentId).FirstOrDefault().FunctionNumber : "";
                        item.Children = GetFunctionInfoTreeList(item.Id);
                    });
                }
            }
            catch
            {

            }
            return resultListDto;
        }

        /// <summary>
        /// 获取信息List
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<GetFunctionInfoDto>> GetFunctionInfoList(GetFunctionInfoQuery query)
        {
            PagePagingDto<GetFunctionInfoDto> pagePagingDto = new PagePagingDto<GetFunctionInfoDto>();
            try
            {
                var functioninfolist = (await _functionInfoRepository.GetAllListAsync(info => info.IsDeleted == false && info.States == true && info.FunctionIsAvailable == true))
                    .WhereIf(!string.IsNullOrEmpty(query.FunctionName), info => info.FunctionName.Contains(query.FunctionName))
                    .WhereIf(!string.IsNullOrEmpty(query.FunctionNumber), info => info.FunctionNumber.Contains(query.FunctionNumber))
                    .OrderByDescending(info => info.CreateTime)
                    .ToList();
                var functioninfopage = functioninfolist
                  .Skip((query.PageIndex - 1) * query.PageSize)
                  .Take(query.PageSize)
                 .ToList();
                if (functioninfopage != null && functioninfopage.Count > 0)
                {
                    pagePagingDto.IsSuccess = true;
                    pagePagingDto.Code = HttpResultCode.Success;
                    pagePagingDto.Message = "查询成功！";
                    pagePagingDto.TotalCount = functioninfolist.Count;
                    var functioninfopagedto = ObjectMapper.Map<List<GetFunctionInfoDto>>(functioninfopage);
                    var funclist = await _functionInfoRepository.GetAllListAsync();
                    functioninfopagedto.ForEach(item =>
                    {
                        item.ParentName = item.ParentId != Guid.Empty ? funclist.Where(info => info.Id == item.ParentId).FirstOrDefault().FunctionName : "";
                        item.ParentNumber = item.ParentId != Guid.Empty ? funclist.Where(info => info.Id == item.ParentId).FirstOrDefault().FunctionNumber : "";
                    });
                    pagePagingDto.Data = functioninfopagedto;
                }
                else
                {
                    pagePagingDto.IsSuccess = false;
                    pagePagingDto.Code = HttpResultCode.SqlError;
                    pagePagingDto.Message = "未查询到相关功能信息！";
                }
            }
            catch (Exception e)
            {
                pagePagingDto.IsSuccess = false;
                pagePagingDto.Code = HttpResultCode.Error;
                pagePagingDto.Message = e.Message.ToString();
            }
            return pagePagingDto;
        }

        /// <summary>
        /// 批量/单个修改状态
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> FunctionInfoBatchChangeOfStatus(FunctionInfoBatchChangeOfStatusQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.SqlError;
                int failnumber = 0;//更新失败数量
                string failid = "";//更新失败Id
                if (query.List != null && query.List.Count > 0)
                {
                    List<Guid> idlist = new List<Guid>();
                    query.List.ForEach(item => { idlist.Add(item.Id); });
                    for (int i = 0; i < idlist.Count; i++)
                    {
                        var functionInfo = await _functionInfoRepository.FirstOrDefaultAsync(info => info.Id == idlist[i]);
                        if (functionInfo != null)
                        {
                            functionInfo.States = query.States;
                            functionInfo.UpdateTime = DateTime.Now;
                            functionInfo.UpdateUserId = token.Id;
                            await _functionInfoRepository.UpdateAsync(functionInfo);
                            baseResultDto.IsSuccess = true;
                            baseResultDto.Code = HttpResultCode.Success;
                            baseResultDto.Message = "更改成功！";
                        }
                        else
                        {
                            failnumber++;
                            failid += string.IsNullOrEmpty(failid) ? idlist[i].ToString() : "," + idlist[i].ToString();
                            baseResultDto.Message = string.Format("一共更新{0}条，失败{1}条,失败id:{2}!", idlist.Count.ToString(), failid.ToString(), failid);
                        }
                    }
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.Message = "IDList不能为空！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 跟新信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdateFunctionInfo(UpdateFunctionInfoQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var functionInfo = await _functionInfoRepository.FirstOrDefaultAsync(info => info.Id == query.Id);
                if (functionInfo != null)
                {
                    if (!string.IsNullOrEmpty(query.FunctionName))
                    {
                        functionInfo.FunctionName = query.FunctionName;
                    }
                    if (!string.IsNullOrEmpty(query.FunctionTypeName))
                    {
                        functionInfo.FunctionTypeName = query.FunctionTypeName;
                    }
                    if (!string.IsNullOrEmpty(query.FunctionNumber))
                    {
                        functionInfo.FunctionNumber = query.FunctionNumber;
                    }
                    if (!string.IsNullOrEmpty(query.FunctionDescribe))
                    {
                        functionInfo.FunctionDescribe = query.FunctionDescribe;
                    }
                    if (query.States != null)
                    {
                        functionInfo.States = (bool)query.States;
                    }
                    if (query.ParentId != null)
                    {
                        functionInfo.ParentId = (Guid)query.ParentId;
                    }
                    functionInfo.UpdateUserId = token.Id;
                    functionInfo.UpdateTime = DateTime.Now;
                    await _functionInfoRepository.UpdateAsync(functionInfo);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "更改成功！";
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.Message = "未查询到Id数据";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }
    }
}
